<template>
  <my-dialog
    v-model="show"
    :show-mark="false"
    title="申请添加朋友"
    draggable
    :mark-close="false"
    :icon-close="!isLoading"
    :width="350"
  >
    <div ref="applyMainRef">
      <el-scrollbar ref="elScrollRef" :max-height="380" style="margin: 0 -15px 0">
        <div class="apply-main">
          <el-form label-position="top">
            <el-form-item class="form-item" label="添加朋友的申请语">
              <el-input
                ref="appLangeRef"
                v-model.trim="setFriend.applyLan"
                :disabled="isLoading"
                :maxlength="40"
                @blur="blur(0, setFriend.applyLan)"
                @keypress.enter.prevent="($refs.remarkRef as any).focus()"
              />
            </el-form-item>
            <el-form-item class="form-item" label="备注名">
              <el-input
                ref="remarkRef"
                v-model.trim="setFriend.remark"
                :disabled="isLoading"
                maxlength="8"
                @blur="blur(1, setFriend.remark)"
                @keypress.enter.prevent="($refs.tagRef as any).focus()"
              />
            </el-form-item>
            <el-form-item class="form-item" label="分组">
              <el-input
                ref="tagRef"
                v-model.trim="setFriend.tag"
                :disabled="isLoading"
                maxlength="16"
                placeholder="设置分组"
              />
            </el-form-item>
          </el-form>
          <div class="apply-main__tag" v-if="tags.size">
            <el-tag
              v-for="[name, { type }] in tags"
              :key="name"
              :type="type"
              class="tag-item"
              @click="selectTag(name)"
            >
              {{ name }}
            </el-tag>
            <SvgIcon
              v-if="groups.maxPage > 1 && groups.currentPage < groups.maxPage"
              icon-class="more"
              popper-class="more-group"
              @click="requestNextGroup(++groups.currentPage)"
            />
          </div>
          <moments-permission
            :disabled="isLoading"
            v-model="permission"
          ></moments-permission></div
      ></el-scrollbar>
    </div>
    <template #footer>
      <el-button
        :disabled="isLoading"
        type="primary"
        @click="startApply"
        :loading="isLoading"
        style="width: 100%"
        ><template #loading><Loading /></template>确认</el-button
      >
    </template>
  </my-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, nextTick } from "vue";
import { useUserPinia } from "@/pinia/user";
import { useFriendPinia } from "@/pinia/friend";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import type { ElInput } from "element-plus";
import myDialog from "../ui-components/dialog.vue";
import momentsPermission from "@/components/momentsPermission.vue";
import handleToTags from "@/plugins/handleToTags";
import SvgIcon from "../svgIcon/index.vue";
import type { ElScrollbar } from "element-plus";

const props = defineProps<{
  modelValue: boolean;
  nickName: string;
  userId: string;
}>();
const emits = defineEmits<{
  (e: "update:modelValue", show: boolean): void;
}>();

const userStore = useUserPinia();
const friendStore = useFriendPinia();
const { user } = storeToRefs(userStore);
const { groups } = storeToRefs(friendStore);

/**
 * 是否显示该对话框
 */
const show = ref<boolean>(false);
/**
 * 朋友圈权限
 */
const permission = ref<Permission>({
  // 是否允许别人看自己的动态
  disabledOtherLook: false,
  // 是否允许自己看别人的动态
  disabledSelfLook: false,
});
/**
 * 申请添加好友的一系列设置
 */
const setFriend = reactive<{
  applyLan: string;
  remark: string;
  tag: string;
}>({
  applyLan: "",
  remark: "",
  tag: "",
});

/**
 * 重置设置
 */
const resetValue = (): void => {
  Object.keys(setFriend).forEach((key) => {
    if (typeof (setFriend as any)[key] === "string") (setFriend as any)[key] = "";
    else if (typeof (setFriend as any)[key] === "boolean")
      (setFriend as any)[key] = false;
  });
};

/**
 * 给添加朋友申请语输入框于一个ref属性
 */
const appLangeRef = ref<typeof ElInput>();
/**
 * 给备注名输入框于一个ref属性
 */
const remarkRef = ref<typeof ElInput>();

// 处理过后的标签数据
const tags = ref<Map<string, { type: "" | "success" | "info" | "warning" | "danger" }>>(
  new Map(handleToTags(groups.value.value))
);

watch(
  () => show.value,
  (value: boolean) => emits("update:modelValue", value)
);

watch(
  () => props.modelValue,
  (value: boolean) => {
    if (value) {
      (setFriend.applyLan = `我是${user.value.nickName}`),
        (setFriend.remark = `${props.nickName}`);
      tags.value = handleToTags(groups.value.value);
    } else {
      permission.value.disabledOtherLook = false;
      permission.value.disabledSelfLook = false;
    }
    show.value = value;
    if (show.value) setTimeout(() => appLangeRef.value!.focus());
  },
  { immediate: true }
);

/**
 * 输入框失焦时触发的函数
 * @param type - 输入框类型
 */
const blur = (type: number, value: string) =>
  value ||
  (type === 0
    ? (setFriend.applyLan = `我是${user.value.nickName}`)
    : (setFriend.remark = props.nickName));

// 是否正在发送申请中
const isLoading = ref<boolean>(false);

// 选择分组标签
const selectTag = (name: string) => {
  if (!isLoading.value) setFriend.tag = name;
};

// 用户点击确认发送请求
const startApply = () => {
  isLoading.value = true;
  userStore
    .applyAddFriend({
      selfId: user.value.userId,
      otherId: props.userId,
      addFriendProperty: { ...setFriend, ...permission.value },
    })
    .then((code: number) => {
      isLoading.value = false;
      if (code === 1) {
        ElMessage({
          type: "success",
          message: "发送申请成功",
          duration: 1500,
        });
        resetValue();
        show.value = false;
      } else
        ElMessage({
          type: "error",
          message: "发送申请失败",
          duration: 1500,
        });
    })
    .catch(() => {
      isLoading.value = false;
      ElMessage({
        type: "error",
        message: "发送申请失败",
        duration: 1500,
      });
    });
};

// 是否正在请求下一页的分组情况
const isRequestNextPageGroup = ref<boolean>(false);
const elScrollRef = ref<typeof ElScrollbar>();
const applyMainRef = ref<HTMLDivElement>(document.createElement("div"));

// 请求下一页的分组情况
const requestNextGroup = (page: number) => {
  if (!isRequestNextPageGroup.value) {
    isRequestNextPageGroup.value = true;
    friendStore
      .getUserGroups({ page })
      .then((payload: { code: number; value: string[] }) => {
        isRequestNextPageGroup.value = false;
        if (payload.code === 1) {
          const newTagData = handleToTags(payload.value);
          for (const [key, { type }] of newTagData.entries())
            tags.value.set(key, { type });
          const ele = applyMainRef.value.getElementsByClassName(
            "el-scrollbar__wrap"
          )[0] as HTMLElement;
          nextTick(() => {
            const top: number = ele.scrollHeight - ele.offsetHeight;
            top > 0 && nextTick(() => elScrollRef.value!.setScrollTop(top));
          });
        } else
          ElMessage({
            type: "error",
            message: "加载失败",
            duration: 1500,
          });
      })
      .catch(() => {
        isRequestNextPageGroup.value = false;
        ElMessage({
          type: "error",
          message: "加载失败",
          duration: 1500,
        });
      });
  }
};
</script>

<style lang="scss" scoped>
.apply {
  &-main {
    width: 90%;
    margin: 0 auto;

    .form-item {
      margin-bottom: 10px;
    }

    &__tag {
      margin: 15px 0 -6px;

      .tag-item {
        cursor: pointer;
        margin: 0 8px 8px 0;
      }

      .more-group {
        font-size: 23px;
        cursor: pointer;
        margin-left: 6px;
        vertical-align: middle;
      }
    }
  }
}
</style>
